package bajo.src;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.PopupScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.decor.Background;
import net.rim.device.api.ui.decor.BackgroundFactory;

public class Student extends ButtonField implements FieldChangeListener{
	
	public final static Background HIGHLIGHT_BACKGROUND = BackgroundFactory.createSolidBackground(Color.GOLD);
	public final static Background NORMAL_BACKGROUND = BackgroundFactory.createSolidBackground(Color.BLUE);
	public final static Background NOT_USING_BACKGROUND = BackgroundFactory.createSolidBackground(Color.GRAY);
	
	public final static String NEAR = "N";
	public final static String SUBSCRIBED = "S";
	
	private String firstName;
	private String lastName;
	private String id;
	private String picURL;
	private Bitmap userPic;
	
	private LabelField status;
	
	private boolean using = false; // true if this student is using our application
	private boolean near = false; // true if this student is near the user

	public Student(String id, String firstName, String lastName, String picURL){
		super(id);
		this.firstName = firstName;
		this.lastName = lastName;
		this.picURL = picURL;
		this.id = id;
		this.picURL = (picURL.equals("")) ? "" : (picURL + Constants.WIFI_INTERFACE);
		userPic = Bitmap.getBitmapResource("blank_user_pic.jpg");
		
		status = new LabelField();
	
	//	this.setBackground(NORMAL_BACKGROUND);
		this.setChangeListener(this);
	}
	
	public void setProx(boolean near){
		String s = "";
		this.near = near;
		if (near){
			s += NEAR;
			if (using){
				s += SUBSCRIBED;
				this.setBackground(HIGHLIGHT_BACKGROUND);
			}else{
				this.setBackground(NOT_USING_BACKGROUND);
			}
		} else { 
			this.setBackground(NORMAL_BACKGROUND);
		}
		status.setText(s + "test");
		this.invalidate();
	}
	
	public LabelField getStatus() {
		return this.status;
	}
	
	public String getStatusText() {
		String stat = "";
		if (near) {
			stat += NEAR;
			if (using) {
				stat += SUBSCRIBED;
			}
		}
		return stat;
	}
	
	public boolean using(){
		return using;
	}
	
	public void setUsing(boolean b){
		using = b;
	}
	
	public boolean isNear(){
		return near;
	}
	
	public String getID(){
		return this.id;
	}
	
	public String getURL(){
		return this.picURL;
	}
	
	public void setURL(String url){
		this.picURL = url;
	}
	
	public void fieldChanged(Field field, int context) {
		UserInfoScreen popup = new UserInfoScreen();
		UiApplication.getUiApplication().pushScreen(popup);
	}
	
	private class UserPictureField extends Field{
		protected void layout(int width, int height) {
			setExtent(250, 150);
		}

		protected void paint(Graphics graphics) {
			if (userPic != null){
				graphics.drawBitmap(0, 0, 200, 150, userPic, 0, 0);
			}
			
		}
		public void update(){
			this.invalidate();
		}
	}
	
	private class UserInfoScreen extends PopupScreen {
		private UserInfoScreen me = this;
		
		private VerticalFieldManager uiPicInfoManager;
		private UserPictureField uiUserPic;
		private HorizontalFieldManager uiUserInfoOKButtonManager;
		private VerticalFieldManager uiUserInfoManager;
		private LabelField uiUserID, uiUserLastName, uiUserFirstName, uiInProximity;

		public UserInfoScreen() {
			super(new VerticalFieldManager(), Manager.FOCUSABLE);
			Thread t = new Thread(){
				public void run(){
					if (!picURL.equals(""))
						downloadImage();
				}
			};
			t.start();
			
			uiPicInfoManager = new VerticalFieldManager();
			uiUserPic = new UserPictureField();
			uiUserInfoOKButtonManager = new HorizontalFieldManager(Manager.FOCUSABLE);
			uiUserInfoManager = new VerticalFieldManager();
			
			uiUserID = new LabelField("User ID: " + id);
			uiUserLastName = new LabelField("Last Name: " + lastName);
			uiUserFirstName = new LabelField("First Name: " + firstName);
			uiInProximity = new LabelField("Near: " + near);
			
			uiUserInfoManager.add(uiUserID);
			uiUserInfoManager.add(uiUserLastName);
			uiUserInfoManager.add(uiUserFirstName);
			uiUserInfoManager.add(uiInProximity);
	
			// OK button.
			ButtonField okButton = new ButtonField("OK");
			okButton.setChangeListener(new FieldChangeListener() {
				public void fieldChanged(Field field, int context) {
					UiApplication.getUiApplication().popScreen(me);
				}
			});
			
			uiUserInfoOKButtonManager.add(uiUserInfoManager);
			if(!using){
				VerticalFieldManager buttonsManager = new VerticalFieldManager();
				//add invitation button.
				ButtonField invitationButton = new ButtonField("INVITE");
				invitationButton.setChangeListener(new FieldChangeListener() {
					public void fieldChanged(Field field, int context) {
						UiApplication.getUiApplication().popScreen(me);
						URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
						postData.append("login", AppMain.userCredentials.getLogin());
						postData.append("credentials", AppMain.userCredentials.getCredentials());
						postData.append("inviteeLogin", id);
						String url = Constants.BASE_TOMCAT_ADDR + Constants.SEND_INVITATION_SERVLET;
						CallBack callBack = new CallBack(){
							public void function(String[] data){
							}
						};
						HTTPDataThread sendThread = new HTTPDataThread(url, postData, HttpConnection.POST, callBack, false);
						sendThread.start();
					}
				});
				buttonsManager.add(invitationButton);
				buttonsManager.add(okButton);
				uiUserInfoOKButtonManager.add(buttonsManager);
			}
			else {
				uiUserInfoOKButtonManager.add(okButton);
			}
			
			uiPicInfoManager.add(uiUserPic);
			uiPicInfoManager.add(uiUserInfoOKButtonManager);
			
			this.add(uiPicInfoManager);
		}
		
		private void updateUserPic(Bitmap img){
			if (img != null){				
				userPic = img;
			}
			this.invalidate();
			uiUserPic.update();
		}
		
		private void downloadImage(){
			HttpConnection httpCon = null;
			InputStream is = null;
			final int BUFSIZE = 10000;

			try {
				// connect to the server and open a connection to the image
				// file
				httpCon = (HttpConnection) Connector.open(picURL);
				
				if (httpCon.getResponseCode() == HttpConnection.HTTP_OK) {
					// open an input stream to download the image
					is = httpCon.openInputStream();
					// temp variable used to hold the downloaded raw data
					byte[] data = new byte[BUFSIZE];
					int length = 0;
					// used to append the downloaded raw data
					StringBuffer rawResponse = new StringBuffer();
					while (-1 != (length = is.read(data))) {
						rawResponse.append(new String(data, 0, length));
					}
					// get the combined data
					// in this case, image
					byte[] result = rawResponse.toString().getBytes();
					// encode the raw data to Bitmap so we can draw it on
					// screen
					EncodedImage resultImg = EncodedImage.createEncodedImage(result, 0, result.length);
					final Bitmap img = resultImg.getBitmap();

					// schedule the ui thread to draw the downloaded image
					UiApplication.getUiApplication().invokeLater(new Runnable() {
						public void run() {
							updateUserPic(img);
						}
					});
				}
				// close the connections
				// we need to do this because we cache nothing
				// also the url for each image changes since server doesn't
				// do anything
				// server just holds the images
				if (is != null)
					is.close();
				if (httpCon != null)
					httpCon.close();
			} catch (IOException ex) {
				// Handle exception
			}
		}
	}
}
